package com.txl.mycamera.filter;

import android.content.Context;
import android.opengl.GLES20;

import com.txl.mycamera.R;
import com.txl.mycamera.utils.OpenGLUtils;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import static com.txl.mycamera.utils.OpenGLUtils.TEXTURE;
import static com.txl.mycamera.utils.OpenGLUtils.VERTEX;

/**
 * @ProjectName: MyCamera
 * @Package: com.txl.mycamera.filter
 * @ClassName: CamreaFilter
 * @Description: java类作用描述
 * @Author: Tao.xiaolong
 * @CreateDate: 2021-04-22 22:29
 * @UpdateUser: 更新者：
 * @UpdateDate: 2021-04-22 22:29
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public class CamreaFilter {

    private int vPositon;
    private int vCoord;
    private int vTexture;
    private int vMatrix;
    private int program;
    private FloatBuffer vertexBuffer;
    private FloatBuffer textureBuffer;

    public CamreaFilter(Context context) {
        String vertexShader = OpenGLUtils.readRawFile(context, R.raw.camera_vert);
        String fragShader = OpenGLUtils.readRawFile(context, R.raw.camera_frag);
        program = OpenGLUtils.buildProgram(vertexShader, fragShader);
        GLES20.glUseProgram(program);
        vPositon = GLES20.glGetAttribLocation(program, "vPositon");
        vCoord = GLES20.glGetAttribLocation(program, "vCoord");
        vTexture = GLES20.glGetUniformLocation(program, "vTexture");
        vMatrix = GLES20.glGetUniformLocation(program, "vMatrix");

        vertexBuffer = ByteBuffer.allocate(VERTEX.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
        vertexBuffer.clear();
        vertexBuffer.put(VERTEX).position(0);


        textureBuffer = ByteBuffer.allocate(TEXTURE.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
        textureBuffer.clear();
        textureBuffer.put(TEXTURE).position(0);
    }

    public void onDraw(float[] mtx, int texture) {
        vertexBuffer.position(0);
        GLES20.glVertexAttribPointer(vPositon, 2, GLES20.GL_FLOAT, false, 0, vertexBuffer);
        GLES20.glEnableVertexAttribArray(vPositon);

        textureBuffer.position(0);
        GLES20.glVertexAttribPointer(vCoord, 2, GLES20.GL_FLOAT, false, 0, textureBuffer);
        GLES20.glEnableVertexAttribArray(vCoord);

        //相当于激活一个用于显示图片的画框

        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture);
        GLES20.glUniform1i(vTexture, 0);

        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
    }


    public void release() {
        GLES20.glDeleteProgram(program);
    }
}
